#include <iostream>
#include <unistd.h>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

void Usage(std::string proc)
{
    std::cout << "\nUsage:\t" << proc << " serverip serverport \n"
              << std::endl;
}
// ./udpclient serverip serverport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    /*  三种字符串转网络序列 */
    // inet_aton(serverip.c_str(),&(server.sin_addr));
    // in_addr_t strip = inet_addr(serverip.c_str());
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    while (true)
    {
        int sockfd = 0;
        int cnt = 5;
        bool isreconnect = false;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cout << "sockfd create error...  errno:" << errno << "  errstring:" << strerror(errno) << std::endl;
            return 1;
        }
        do
        {
            // 客户端必须bind端口才能进行通信，但是多个软件的使用端口一致会导致冲突，不能自己显式的bind端口
            // 使用connect函数，OS会自动进行分配端口
            int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                cnt--;
                isreconnect = true;
                std::cerr << "connect error...,reconnect: " << cnt << std::endl;
                close(sockfd);
                sleep(2);
            }
            else
                break;
        } while (cnt && isreconnect);
        if (cnt == 0)
        {
            std::cerr << "use offline..." << std::endl;
            break;
        }
        // while (true)
        // {
            std::string message;
            std::cout << "Please Enter# ";
            getline(std::cin, message);
            int n = write(sockfd, message.c_str(), message.size());
            if (n < 0)
            {
                isreconnect = true;
                std::cerr << "write error..." << std::endl;
                //break;
            }
            char inbuffer[4096];
            n = read(sockfd, inbuffer, sizeof(inbuffer));
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
        //     else break;
        // }
        close(sockfd);
    }
    return 0;
}
